package cn.mumzone.pos.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.netstatus.NetUtils;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.IsFastClickUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.AddGoodsEvent;
import cn.mumzone.pos.event.RemotePriceChangeEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.presenter.GoodsSoldPresenter;
import cn.mumzone.pos.presenter.contract.GoodsSoldContract;
import cn.mumzone.pos.ui.activity.ACT_OpenOrder;
import cn.mumzone.pos.ui.adapter.ADA_GoodsSoldList;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnLoadMoreListener;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.PopupUtil;
import retrofit2.http.POST;

public class FRA_OpenOrderGoods extends BaseFragment<GoodsSoldPresenter> implements GoodsSoldContract.View {

    @BindView(R.id.et_search_goods)
    EditText etSearchGoods;
    @BindView(R.id.rv_goods_list)
    LRecyclerView rvGoodsList;

    @BindView(R.id.ll_empty_goods)
    LinearLayout llEmptyGoods;
    @BindView(R.id.iv_empty_goods)
    AppCompatImageView ivEmptyGoods;
    @BindView(R.id.tv_goods_empty)
    TextView tvGoodsEmpty;
    @BindView(R.id.tv_goods_empty_hint)
    TextView tvGoodsEmptyHint;

    @BindView(R.id.tv_goods_title_info)
    TextView tvTitleGoodsInfo;
    @BindView(R.id.tv_goods_title_search)
    TextView tvTitleSearchResult;

    @BindView(R.id.et_scan)
    EditText etScan;

    @BindView(R.id.rb_search)
    RadioButton rbSearch;

    @BindView(R.id.iv_clear_input)
    AppCompatImageView ivClearInput;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.ll_container)
    LinearLayout llContainer;

    // 当前是否正在执行扫码，防止过快扫描
    private boolean isScanExecuted;

    private ADA_GoodsSoldList mGoodsAdapter;

    @Override
    protected void onUserVisible() {
        etScan.requestFocus();
    }

    @Override
    protected void initEventAndData() {

        initRecyclerView();

        toggleEmptyLayout(true, true);

        initScanCodeRelated();

        mPresenter.initEvent();

        llContainer.postDelayed(new Runnable() {
            @Override
            public void run() {
//                PopupUtil.showBlackBgPopup(tvTitleGoodsInfo, "网络不给力", PopupUtil.RIGHT_BOTTOM);
//                PopupUtil.showBlackBgPopup(tvTitleGoodsInfo, "网络不给力", PopupUtil.RIGHT);
            }
        }, 2000);

    }

    private void initRecyclerView() {

        // basic
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        rvGoodsList.setLayoutManager(manager);
        mGoodsAdapter = new ADA_GoodsSoldList(mContext);
        rvGoodsList.setAdapter(new LRecyclerViewAdapter(mGoodsAdapter));
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_6)
                .setColorResource(android.R.color.transparent)
                .build();
        rvGoodsList.addItemDecoration(divider);
        rvGoodsList.setHasFixedSize(true);
        rvGoodsList.setPullRefreshEnabled(false);
        rvGoodsList.setLoadMoreEnabled(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.searchGoodsInfo(etSearchGoods.getText().toString(), true, false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.searchGoodsInfo(etSearchGoods.getText().toString(), false, false);
            }
        });

        ItemClickSupport.addTo(rvGoodsList)
                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                        List<GoodsEntity> goodsList = mGoodsAdapter.getDataList();
                        GoodsEntity selectedEntity = goodsList.get(position - 1);
                        if (!StringUtils.isTrue(selectedEntity.getStockGoods())) {
                            postGoodsListToActivity(selectedEntity, null);
                        } else {
                            showError("商品未入库，无法售卖~");
                        }
                    }
                });

    }

    /**
     * 初始化扫码工作
     */
    private void initScanCodeRelated() {

        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearchGoods, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();

                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {
                    Elog.e("SCAN------> ", "code: " + code);

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.searchGoodsInfo(code, true, true);
                    }
                    isScanExecuted = true;
                }
                etScan.setText("");
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearchGoods.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });
        etSearchGoods.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);
                    refreshLayout.autoRefresh();
                }
                return false;
            }
        });
    }

    @OnClick({R.id.rb_search, R.id.iv_clear_input})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_search:
                refreshLayout.autoRefresh();
                break;
            case R.id.iv_clear_input:
                etSearchGoods.setText("");
                mGoodsAdapter.getDataList().clear();
                toggleEmptyLayout(true, true);
                break;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_open_order_goods;
    }

    @Override
    public void showSearchGoodsList(List<GoodsEntity> entitys, boolean isRefresh) {

        ACT_OpenOrder rootActivity = (ACT_OpenOrder) getActivity();
        GoodsUtil.syncLocalAndRemotePrice(entitys, rootActivity.getCartList());
        RxBus.getDefault().post(new RemotePriceChangeEvent(RemotePriceChangeEvent.TYPE_GOODS));

        // 当前搜索结果来自扫码
        if (isScanExecuted) {

            // 重置扫码状态，允许再次扫码
            isScanExecuted = false;

            if (ListUtil.isListEmpty(entitys)) {
                ToastUtil.makeText(mContext, "未搜索到该商品", false);
            } else if (entitys.size() == 1) {
                GoodsEntity entity = entitys.get(0);
                if (!StringUtils.isTrue(entity.getStockGoods())) {
                    postGoodsListToActivity(null, entitys);
                } else {
                    showError("商品未入库，无法售卖~");
                }
            } else {

                LinkedList<GoodsEntity> localCartList = rootActivity.getCartList();
                boolean isBindMember = rootActivity.getSelectMember() != null &&
                        !StringUtils.isEmpty(rootActivity.getSelectMember().getMemberId());
                GoodsUtil.showGoodsSelectDialog(mContext,
                        isBindMember,
                        localCartList, entitys, new GoodsUtil.OnSelectedMultipleGoodsListener() {
                            @Override
                            public void OnSelectedMultipleGoods(List<GoodsEntity> selectedList) {
                                postGoodsListToActivity(null, selectedList);
                            }
                        });

            }

            return;
        }

        // 停止刷新
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();

        // 搜索结果来自于手动搜索，支持刷新和加载
        if (!ListUtil.isListEmpty(entitys)) {

            // 匹配购物车中已有数据，将已选角标数量反显
            LinkedList<GoodsEntity> cartList = rootActivity.getCartList();
            for (GoodsEntity cartGoodsEntity : cartList) {
                for (GoodsEntity requestGoodsEntity : entitys) {
                    if (requestGoodsEntity.getGoodsSkuId().equals(cartGoodsEntity.getGoodsSkuId())) {
                        requestGoodsEntity.setSelectCount(cartGoodsEntity.getSelectCount());
                        break;
                    }
                }
            }
        }
        mGoodsAdapter.update(entitys, isRefresh);

        toggleEmptyLayout(ListUtil.isListEmpty(mGoodsAdapter.getDataList()), true);

    }

    @Override
    public void showAddGoodsSuccess() { /* 开单页面，添加商品到购物车不是在 fragment 完成的，此回调无用 */ }

    @Override
    public void showClearCart() { /* 暂时没有清空购物车功能 */ }


    @Override
    public void onGoodsAmountChanged(List<GoodsEntity> cartList) {
        LinkedList<GoodsEntity> localCartList = ((ACT_OpenOrder) getActivity()).getCartList();
        GoodsUtil.updateGoodsSelectStatus(mGoodsAdapter, mGoodsAdapter.getDataList(), localCartList);
    }

    @Override
    public void showMemberBindStatusChanged(MemberEntity memberEntity) {
        // 绑定、解绑会员或者更改会员信息后，刷新页面
        mGoodsAdapter.setBindMember(memberEntity);
        refreshLayout.autoRefresh();
//        mGoodsAdapter.notifyDataSetChanged();
    }

    @Override
    public void showSearchGoodsError(String msg) {
        if (isScanExecuted) {
            isScanExecuted = false;
            PosToast.INSTANCE.makeShortToast(mContext, msg);
            return;
        }

        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }

        toggleEmptyLayout(true, false);
    }

    @Override
    public void showError(String msg) {
        if (isScanExecuted) {
            isScanExecuted = false;
        }
        super.showError(msg);
        if (isScanExecuted) {
            isScanExecuted = false;
        }

        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
    }

    /**
     * 将选中的 GoodsEntity 统一给 Activity 处理
     *
     * @param entity
     * @param list
     */
    private void postGoodsListToActivity(GoodsEntity entity, List<GoodsEntity> list) {

        LinkedList<GoodsEntity> localCartList = ((ACT_OpenOrder) getActivity()).getCartList();
        List<GoodsEntity> postList = GoodsUtil.prepareToAddGoodsToCart(mContext, localCartList, entity, list);
        if (!ListUtil.isListEmpty(postList)) {
            RxBus.getDefault().post(new AddGoodsEvent(postList));
        }

    }

    public boolean toggleEmptyLayout(boolean isEmpty, boolean isDataEmpty) {
        if (isEmpty) {
            // 商品信息 + 空页面
            tvTitleGoodsInfo.setVisibility(View.VISIBLE);
            llEmptyGoods.setVisibility(View.VISIBLE);
            // 搜索结果 + 列表
            tvTitleSearchResult.setVisibility(View.GONE);
            rvGoodsList.setVisibility(View.GONE);

            ivEmptyGoods.setImageResource(isDataEmpty ? R.mipmap.ic_cash_service_empty : R.mipmap.ic_cash_service_empty_search);
            tvGoodsEmpty.setText(isDataEmpty ? "暂无商品信息" : "没有找到任何内容");
            tvGoodsEmptyHint.setText(isDataEmpty ? "您可以在后台配置商品信息" : "你可以换个关键词试试~");
            tvGoodsEmptyHint.setTextColor(isDataEmpty ? getResources().getColor(R.color.order_status_service) :
                    getResources().getColor(R.color.content_text_color));
            tvGoodsEmptyHint.setCompoundDrawablesWithIntrinsicBounds(isDataEmpty ?
                            getResources().getDrawable(R.drawable.svg_ic_alert_remind) : null,
                    null, null, null);

        } else {
            // 商品信息 + 空页面
            tvTitleGoodsInfo.setVisibility(View.GONE);
            llEmptyGoods.setVisibility(View.GONE);
            // 搜索结果 + 列表
            tvTitleSearchResult.setVisibility(View.VISIBLE);
            rvGoodsList.setVisibility(View.VISIBLE);
        }
        return isEmpty;
    }

    @Override
    protected void refreshNetwork() {
        refreshLayout.autoRefresh();
    }

    @Override
    public void showNetError() {
        refreshLayout.finishRefresh();
        if (ListUtil.isListEmpty(mGoodsAdapter.getDataList())) {
            super.showNetError();
        } else {
            PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍后重试");
        }
    }

    @Override
    protected View getTargetView() {
        return llContainer;
    }
}
